home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Delphi Magazine Collection 2001
/
Delphi Magazine Collection 20001 (2001).iso
/
DISKS
/
Issue55
/
Alfresco
/
TestRW.dpr
< prev
Wrap
Text File
|
2000-02-10
|
3KB
|
122 lines
program TestRW;
{$APPTYPE CONSOLE}
uses
Windows,
SysUtils,
Classes,
AAThread;
type
TWriterThread = class(TThread)
private
FId : integer;
protected
procedure Execute; override;
public
property Id : integer read FId write FId;
end;
TReaderThread = class(TThread)
private
FId : integer;
protected
procedure Execute; override;
public
property Id : integer read FId write FId;
end;
var
ReadWriteSync : TaaReadWriteSync;
Log : text;
LogCS : TRTLCriticalSection;
procedure SafeWriteln(aMsg : string);
begin
EnterCriticalSection(LogCS);
writeln(Log, aMsg);
LeaveCriticalSection(LogCS);
end;
procedure TWriterThread.Execute;
var
i : integer;
begin
for i := 1 to 100 do begin
ReadWriteSync.StartWriting;
writeln(Log, 'writer active: ', Id);
write(Id);
ReadWriteSync.StopWriting;
end;
end;
procedure TReaderThread.Execute;
var
i : integer;
begin
for i := 1 to 50 do begin
ReadWriteSync.StartReading;
SafeWriteln(Format('reader active: %d', [Id]));
Sleep(Random(500));
ReadWriteSync.StopReading;
end;
end;
var
Readers : array [0..6] of TReaderThread;
Writers : array [0..2] of TWriterThread;
i : integer;
Handles : array [0..9] of THandle;
begin
writeln('Starting test');
writeln('(Writers show their id in this window when writing)');
{create the log file}
Assign(Log, 'C:\Thread.LOG');
Rewrite(Log);
InitializeCriticalSection(LogCS);
{create the sync object}
ReadWriteSync := TaaReadWriteSync.Create;
{set up 7 readers and 3 writers}
for i := 0 to 6 do begin
Readers[i] := TReaderThread.Create(true);
Readers[i].Id := i;
end;
for i := 0 to 2 do begin
Writers[i] := TWriterThread.Create(true);
Writers[i].Id := i;
end;
{save the handles for the wait for multiple objects call}
for i := 0 to 6 do
Handles[i] := Readers[i].Handle;
for i := 0 to 2 do
Handles[7+i] := Writers[i].Handle;
{start the whole lot going}
for i := 0 to 2 do
Writers[i].Resume;
for i := 0 to 6 do
Readers[i].Resume;
{wait for them all to finish}
WaitForMultipleObjects(10, @Handles, true, INFINITE);
{destroy the thread objects (they've all completed)}
for i := 0 to 6 do
Readers[i].Free;
for i := 0 to 2 do
Writers[i].Free;
{close the log file}
DeleteCriticalSection(LogCS);
Close(Log);
writeln;
writeln('Done');
readln;
end.